import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { BookEntity } from './books.entity';
import { CommonObjectProps } from '../../types/obj-type';

@Injectable()
export class BooksService {
  constructor(
    @InjectRepository(BookEntity)
    private readonly booksRepository: Repository<BookEntity>,
  ) {}

  async addBook(book: CommonObjectProps): Promise<BookEntity> {
    return await this.booksRepository.save(book);
  }

  async books(bookReqDto: {
    id?: string | number;
    name?: string;
    author?: string;
    category?: string;
  }): Promise<BookEntity[]> {
    console.log('请求参数', bookReqDto);

    const { id, name, author, category } = bookReqDto || {};
    const where: any = {};
    if (id) where.id = id;
    if (name) where.name = name;
    if (author) where.author = author;
    if (category) where.category = category;

    return await this.booksRepository.find({ relations: ['reader'], where });
  }

  // 查单个
  async getBook(id: number): Promise<BookEntity> {
    // @ts-ignore
    return await this.booksRepository.findOne({ where: { id } });
  }

  // 更新
  async update(id: number, book: CommonObjectProps) {
    const result = await getConnection()
      .createQueryBuilder()
      .update(BookEntity)
      .set(book)
      .where('id=:id', { id })
      .execute();
    return result;
  }

  // 删除
  async delete(id: number) {
    const result = await getConnection()
      .createQueryBuilder()
      .delete()
      .from(BookEntity)
      .where('id=:id', { id })
      .execute();
    return result;
  }
}
